package com.resys.server.interceptor;


import com.resys.entity.enums.ResponseCodeEnum;
import com.resys.exception.BusinessException;
import com.resys.server.component.RedisComponent;
import com.resys.utils.StringTools;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AppInterceptor implements HandlerInterceptor {
    @Resource
    private RedisComponent redisComponent;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if(handler==null){
            return false;
        }
        if(request.getRequestURI().contains("/account")){
                return true;
        }
        String token = getTokenFromCookie(request);
        if(token==null){
            throw new BusinessException(ResponseCodeEnum.CODE_901);
        }

        Object sessionObj = redisComponent.getTokenInfo(token,"admin");
        if(sessionObj==null){
            throw new BusinessException(ResponseCodeEnum.CODE_901);
        }
        return true;
    }
    private String getTokenFromCookie(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        if(cookies==null){
            return null;
        }
        String token = null;
        for(Cookie cookie : cookies) {
            if(cookie.getName().equals("tokenadmin")) {
               return cookie.getValue();
            }
        }
       return null;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
